<template>
  <section style="height: 90vh;display: flex;">
    <el-row :gutter="25" style="display: flex; flex-grow: 1;">
      <!-- 左侧区域 -->
      <el-col :span="8" style="height: 100%;margin-top: 20px;">
        <el-card style="height: 90%;">
          <el-tree
              :data="treeData"
              :props="treeProps"
              accordion
              highlight-current
              node-key="id"
              @node-click="handleNodeClick"
          ></el-tree>
        </el-card>
      </el-col>
      <!-- 右侧区域 -->
      <!--工具条-->
      <el-col :span="16" class="toolbar" style="height: 90%; display: flex; flex-direction: column;">
        <el-card style="flex-grow: 1;">
          <el-form :inline="true" :model="searchMsg" size="small">
            <el-col :span="8">
              <el-input
                  v-model="usernameFilter"
                  clearable
                  placeholder="根据用户名筛选"
                  @input="handleUsernameFilter"
              />
            </el-col>
            <el-col :span="8">
              <el-input
                  v-model="schoolCodeFilter"
                  clearable
                  placeholder="根据学校筛选"
                  @input="handleSchoolCodeFilter"
              />
            </el-col>
            <el-form-item>
              <el-button type="primary" @click="resetFilter">重置筛选</el-button>
              <el-button icon="el-icon-plus" type="primary" @click="handleAdd()">新增管理员</el-button>
            </el-form-item>
          </el-form>

          <!--列表-->
          <el-table v-loading="listLoading" :cell-style="cellStyle" :data="filteredNodes"
                    :header-cell-style="headerCellStyle"
                    highlight-current-row style="width: 100%;">
            <el-table-column label="管理员名称" prop="username"></el-table-column>
            <el-table-column label="学校" prop="schoolCode"></el-table-column>
            <el-table-column label="父节点" prop="parentId"></el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
              <template slot-scope="scope">
                <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <!--工具条-->
        <el-col :span="24" class="toolbar">
          <el-pagination
              :page-size="searchMsg.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              style="float:right;"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange">
          </el-pagination>
        </el-col>
      </el-col>
    </el-row>

    <!--编辑管理员-->
    <el-dialog :title="editTitle" :visible.sync="editFormVisible">
      <el-form ref="editForm" :model="editForm" label-width="150px">
        <el-form-item label="管理员名称" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="学校" prop="schoolCode">
          <el-input v-model="editForm.schoolCode"></el-input>
        </el-form-item>
        <el-form-item label="父节点" prop="parentId">
          <el-input v-model="editForm.parentId"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit">提交</el-button>
      </div>
    </el-dialog>
    <!--新增管理员-->
    <el-dialog :title="addTitle" :visible.sync="addFormVisible">
      <el-form ref="addForm" :model="addForm" label-width="150px">
        <el-form-item label="管理员名称" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="学校" prop="schoolCode">
          <el-input v-model="addForm.schoolCode"></el-input>
        </el-form-item>
        <el-form-item label="父节点" prop="parentId">
          <el-input v-model="addForm.parentId"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
export default {
  data() {
    return {
      treeData: [], // 用于保存树形数据
      list: [],
      filteredNodes: [],
      treeProps: {
        children: 'children',
        label: 'username' // 用哪个字段作为树节点的显示名称
      },
      searchMsg: {
        pageNo: 1,
        pageSize: 20
      },
      total: 0,
      editFormVisible: false,
      editTitle: '编辑管理员',
      addFormVisible: false,
      addTitle: '新增管理员',
      editForm: {
        username: '',
        schoolCode: '',
        parentId: '',
      },
      addForm: {
        username: '',
        mobile: '',
        schoolCode: '',
        parentId: '',
      },
      timer: null,
      usernameFilter: '',
      schoolCodeFilter: '',
    }
  },
  methods: {
    cellStyle({row, column, rowIndex, columnIndex}) {
      return "text-align:center";
    },
    headerCellStyle({row, rowIndex}) {
      return "text-align:center";
    },

    getList() {
      let vue = this;
      let param = Object.assign({}, vue.searchMsg);
      vue.listLoading = true;
      vue.$http.post(vue, '/rest/admin/list', param,
          (vue, data) => {
            vue.listLoading = false;
            vue.list = data.data.records;
            vue.total = data.data.total;
            vue.treeData = vue.buildTree(vue.list);
            vue.filteredNodes = vue.list;
          }, (error, data) => {
            vue.listLoading = false;
            vue.$message({
              showClose: true,
              message: data.message,
              type: 'error'
            });
          }
      );
    },

    buildTree(list) {
      let map = {};
      let tree = [];
      list.forEach(item => {
        map[item.id] = {...item, children: []};
      });
      list.forEach(item => {
        if (item.parentId === null || item.parentId === 0) {
          tree.push(map[item.id]);
        } else {
          if (map[item.parentId]) {
            map[item.parentId].children.push(map[item.id]);
          }
        }
      });
      return tree;
    },

    handleNodeClick(node) {
      const selectedNodeIds = this.getAllChildNodes(node);
      this.filterNodesById(selectedNodeIds);
    },

    getAllChildNodes(node) {
      let ids = [node.id];
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          ids = ids.concat(this.getAllChildNodes(child));
        });
      }
      return ids;
    },

    filterNodesById(ids) {
      this.filteredNodes = this.list.filter(item => ids.includes(item.id));
    },

    resetFilter() {
      this.usernameFilter = '';
      this.schoolCodeFilter = '';
      this.filteredNodes = this.list; // 显示所有节点
    },

    handleUsernameFilter() {
      this.filteredNodes = this.list.filter(item => {
        const matchesUsername = item.username.includes(this.usernameFilter);
        return matchesUsername;
      });
    },
    handleSchoolCodeFilter() {
      this.filteredNodes = this.list.filter(item => {
        const matchesSchoolCode = item.schoolCode.includes(this.schoolCodeFilter);
        return matchesSchoolCode;
      });
    },

    handleEdit(row) {
      this.editFormVisible = true;
      this.editForm.id = row.id;
      this.editForm.username = row.username;
      this.editForm.schoolCode = row.schoolCode;
      this.editForm.parentId = row.parentId;
    },

    editSubmit() {//编辑账户
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          let vue = this;
          let param = Object.assign(vue.editForm);
          vue.$http.post(vue, '/rest/admin/updateSelective', param,
              (vue, data) => {
                vue.$message({
                  showClose: true,
                  message: data.message,
                  type: 'success'
                });
                vue.getList();
                vue.$refs['editForm'].resetFields();
                vue.editFormVisible = false;
              }, (error, data) => {
                vue.editFormVisible = false;
                vue.$message({
                  showClose: true,
                  message: data.message,
                  type: 'error'
                });
              })
        }
      })
    },
    handleAdd() {
      this.addFormVisible = true;
      this.addForm.username = row.username
      this.addForm.mobile = row.mobile
      this.addForm.schoolCode = row.schoolCode
      this.addForm.parentId = row.parentId
    },
    addSubmit() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let vue = this;
          let param = Object.assign({}, this.addForm);
          let url = "/rest/admin/add";
          vue.$http.post(vue, url, param,
              (vue, data) => {
                vue.$message({
                  showClose: true,
                  message: '注册成功',
                  type: 'success'
                });
                vue.getList()
                vue.addFormVisible = false;
              }, (error, data) => {
                vue.$message({
                  showClose: true,
                  message: data.message,
                  type: 'error'
                });
              })
        } else {
          this.$message.error('表单校验失败，请检查输入内容！');
        }
      })
    },

    handleDelete(row) {
      this.$confirm('确认删除该账户吗?', '提示', {
        type: 'warning'
      }).then(() => {
        let vue = this;
        let param = {
          id: row.id
        }
        vue.$http.post(vue, '/rest/admin/delete', param,
            (vue, data) => {
              vue.$message({
                showClose: true,
                message: data.message,
                type: 'success'
              });
              vue.getList();
            }, (error, data) => {
              vue.$message({
                showClose: true,
                message: data.message,
                type: 'error'
              });
            })
      }).catch(() => {
      });
    },
    handleSizeChange(val) {
      this.searchMsg.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.searchMsg.pageNo = val;
      this.getList();
    }
  },
  mounted() {
    this.getList();
    this.$orderPrint.init();
  }
}

</script>

<style scoped>

</style>
